﻿using System.Collections.ObjectModel;
using CommunityToolkit.Mvvm.ComponentModel;
using WhaleAccount.Contracts.ViewModels;
using WhaleAccount.Contracts.Services;
using WhaleAccount.Models;

namespace WhaleAccount.ViewModels;

public class MainViewModel : ObservableRecipient, INavigationAware
{
    private readonly IRecordService _recordService;
    private DayRecordSummary? _selected;
    private MonthRecordSummary _monthRecordSummary;

    public DayRecordSummary? Selected
    {
        get => _selected;
        set => SetProperty(ref _selected, value);
    }

    public MonthRecordSummary MonthRecordSummary
    {
        get => _monthRecordSummary;
        set => SetProperty(ref _monthRecordSummary, value);
    }

    public ObservableCollection<DayRecordSummary> DayRecordSummaryList
    {
        get;
        private set;
    } = new ObservableCollection<DayRecordSummary>();

    public MainViewModel(IRecordService recordService)
    {
        _monthRecordSummary = new MonthRecordSummary();
        _recordService = recordService;
    }

    public void OnNavigatedTo(object parameter)
    {
        LoadData(DateTime.Now.Year, DateTime.Now.Month);
    }

    public async void LoadData(int year, int month)
    {
        DayRecordSummaryList.Clear();

        var data = await _recordService.GetDayRecordSummaryListAsync(year, month);
        double income = 0;
        double expense = 0;

        foreach (var item in data)
        {
            DayRecordSummaryList.Add(item);
            income += item.Income;
            expense += item.Expense;
        }

        MonthRecordSummary.Date = new DateTime(year, month, 1);
        MonthRecordSummary.Income = income;
        MonthRecordSummary.Expense = expense;
    }

    public void OnNavigatedFrom()
    {
    }

    public void EnsureItemSelected()
    {
        if (DayRecordSummaryList.Count > 0)
        {
            Selected ??= DayRecordSummaryList.First();
        }
    }

    public void EnsureItemSelected(DateTime date)
    {
        if (DayRecordSummaryList.Count > 0)
        {
            Selected = (from day in DayRecordSummaryList
                                    where day.Date.Year == date.Year
                                    && day.Date.Month == date.Month
                                    && day.Date.Day == date.Day
                                    select day).FirstOrDefault();
        }
    }

    public void Calculate()
    {
        double income = 0;
        double expense = 0;
        foreach (var dayRecordSummary in DayRecordSummaryList)
        {
            income += dayRecordSummary.Income;
            expense += dayRecordSummary.Expense;
        }

        MonthRecordSummary.Income = income;
        MonthRecordSummary.Expense = expense;
    }
}
